package org.example.word;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static org.example.word.CreateWordXWPFHyperlinkRun.createHyperlinkRun;

public class WriteWordDemo1 {
    public static final String FILE_URL = "https://blog.csdn.net/oy538730875/article/details/84683551";
    public static void main(String[] args) {
    //
        try (FileInputStream inputStream = new FileInputStream(new File("E:\\work_template\\word1.docx"))) {
            XWPFDocument document = new XWPFDocument(inputStream);
            List<XWPFTable> tables = document.getTables();
            XWPFTable table = tables.get(0);

            XWPFTableRow oldRow1 = table.getRow(13);
            CTRow ctRow1 = CTRow.Factory.parse(oldRow1.getCtRow().newInputStream());
            XWPFTableRow newRow1 = new XWPFTableRow(ctRow1,table);

            XWPFParagraph paragraph = newRow1.getCell(1).getParagraphArray(0);
            XWPFRun run = paragraph.createRun();
            run.setText("附件1.docx");
            paragraph.addRun(run);

            XWPFHyperlinkRun hyperlinkrun = createHyperlinkRun(paragraph, "https://www.google.de");
            hyperlinkrun.setText("点击下载");
            hyperlinkrun.setColor("000000");
            hyperlinkrun.setFontFamily("宋体");
            hyperlinkrun.setBold(true);
            paragraph.addRun(hyperlinkrun);

            newRow1.getCell(1).setParagraph(paragraph);

            /*XWPFRun run = paragraph.createRun();

            String id = paragraph.getDocument().getPackagePart()
                    .addExternalRelationship(FILE_URL,XWPFRelation.HYPERLINK.getRelation())
                    .getId();
            CTHyperlink cLink = paragraph.getCTP().addNewHyperlink();
            cLink.setId(id);

            CTText ctText = CTText.Factory.newInstance();
            ctText.setStringValue("点击下载");
            CTR ctr = CTR.Factory.newInstance();
            CTRPr ctrPr = ctr.addNewRPr();

            ctr.setTArray(new CTText[]{ctText});
            cLink.setRArray(new CTR[]{ctr});
            newRow1.getCell(1).setText("111.docx");
            newRow1.getCell(1).setParagraph(paragraph);*/

            table.addRow(newRow1,20);


            try (FileOutputStream outputStream = new FileOutputStream(new File("E:\\work_template\\" + System.currentTimeMillis() + "_1.docx"))) {
                document.write(outputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void replaceInParagraph(XWPFTableRow row,int pos,String replaceText){
        for(XWPFParagraph p : row.getCell(pos).getParagraphs()){
            for(XWPFRun r : p.getRuns()){
                r.setText(replaceText,0);
            }
        }
    }
}
